package cn.com.bonc.khjy.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    private static StringRedisTemplate redisTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate0;

    @PostConstruct
    public void init() {
        redisTemplate = redisTemplate0;
    }

    /**
     * 获取一个字符串
     */
    public static String get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 设置value
     */
    public static String set(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
        return value;
    }

    /**
     * 设置value，带过期事件，单位：秒
     */
    public static String set(String key, String value, int time) {
        redisTemplate.opsForValue().set(key, value);
        redisTemplate.expire(key, time, TimeUnit.SECONDS);
        return value;
    }

    public static long lSet(String key, List<String> value) {
        redisTemplate.delete(key);
        redisTemplate.opsForList().rightPushAll(key, value);
        return value.size();
    }

    public static List<String> lGet(String key) {
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    public static Set<String> getDirKeys(String dir) {
        return redisTemplate.keys(dir + "*");
    }

    public static boolean hasKey(String key) {

        return redisTemplate.hasKey(key);

    }

    public static void del(String key){
        redisTemplate.delete(key);
    }

    public static void hPut(  String key,   String hKey,   Object value) {
        redisTemplate.opsForHash().put(key, hKey, value);
    }
    public static Object hGet(final String key, final String hKey) {

        return redisTemplate.opsForHash().get(key, hKey);
    }
    public static Map<Object, Object> hmget(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

}